<script lang="ts">
import { useClipboard, useEventListener } from '@peng_kai/kit/libs/vueuse';
import { computed } from 'vue';

function getNthParent(element: HTMLElement, n: number): HTMLElement | null {
  let currentElement: HTMLElement | null = element;

  for (let i = 0; i < n; i++) {
    if (currentElement && currentElement.parentElement)
      currentElement = currentElement.parentElement;
    else
      return null; // 如果在达到指定层数之前遇到null，返回null
  }

  return currentElement;
}
</script>

<script setup lang="ts">
const props = defineProps<{
  /** 被复制的文本内容 */
  source?: any;
  /** 在第几层父级元素上也可触发复制 */
  nthParent?: number;
  /** 触发复制的元素或选择器 */
  trigger?: string | HTMLElement;
}>();

const source = computed(() => String(props.source));
const { copied, copy } = useClipboard({ source, legacy: true });
const $btn = ref<HTMLDivElement>();

const $btnParentEle = computed(() => ($btn.value && props.nthParent) ? getNthParent($btn.value, props.nthParent) : null);
const $triggerEle = computed(() => typeof props.trigger === 'string' ? document.querySelector(props.trigger) : props.trigger);

onMounted(() => {
  useEventListener($btnParentEle, 'click', () => copy(source.value));
  useEventListener($triggerEle, 'click', () => copy(source.value));
});

defineExpose({
  copy: (content: unknown) => copy(String(content) || source.value),
});
</script>

<template>
  <div ref="$btn" class="flex cursor-copy items-center justify-center" @click="copy(source)">
    <slot :copied="copied">
      <slot v-if="copied" name="copied">
        <i class="i-ri:check-fill block text-1.2em text-green" />
      </slot>
      <slot v-else name="idle">
        <i class="i-ri:checkbox-multiple-blank-fill block text-1.2em text-inherit" />
      </slot>
    </slot>
  </div>
</template>
